from flask import render_template,redirect,url_for,session, flash
from flask_login import login_required, current_user
#from flaskext.uploads import UploadSet, IMAGES
from bson.dbref import DBRef

from controller import app
from lib.form import Form

from dao.category import CategoryDao
from dao.subject import SubjectDao


from service.subject import SubjectForm, SubjectService

IMAGES = tuple('jpg jpe jpeg png gif svg bmp'.split())

class SubjectsForm(Form):
    def __init__(self):
        '''Only accept POST request
        '''
        Form.__init__(self)


@app.route('/manage_subjects')
@app.route('/manage_subjects', methods=['GET','POST'])
@login_required
def manage_subjects():
    form = SubjectForm()
    subject_dao = SubjectDao()
    
    if form.is_submitted():
        if form.action == 'edit':
            #subject = subject_dao.update_subject(form.id, form.name, form.description)
            pass
        else:
            subject_dao.save({'body':form.body})
            
            #flash("Image saved.")
            #return redirect(url_for('pictures'))
            return redirect(url_for('display_subjects'))
    return redirect(url_for('display_subjects'))

@app.route('/display_subjects')
@login_required
def display_subjects():
    #return render_template("add_subject-v1.html", subjects=None)
    service = SubjectService()
    subjects = service.get_subject_list()
    return render_template("manage_subjects.html", subjects=subjects)
    
@app.route("/delete_subjects", methods=["GET", "POST"])
@login_required
def delete_subjects():
    subject_dao = SubjectDao()
    
    form = SubjectsForm()
    ids = form.request.form.getlist('selected')
    for _id in ids:
        subject = subject_dao.filter_first(id=int(_id))
        subject_dao.remove_from_db(subject)
        
    return render_template("manage_subjects.html", subjects=subject_dao.all())            
